package com.zyj.test.month1.day5;

/**
 * @author Yijia Zhang
 * @create 2024-04-27 00:03
 */
public class code0007 {
    public int reverse(int x) {
        if (x == 0) {
            return 0;
        }
        String maxStr = String.valueOf(Integer.MAX_VALUE);
        String minStr = String.valueOf(Integer.MIN_VALUE).substring(1);
        if (x > 0) {
            StringBuilder xStr = new StringBuilder(String.valueOf(x));
            String reverseStr = xStr.reverse().toString();

            // 去掉前面的0
            int firstNotZero = 0;
            while (firstNotZero < reverseStr.length() && reverseStr.charAt(firstNotZero) == '0') {
                firstNotZero++;
            }
            reverseStr = reverseStr.substring(firstNotZero);
            if (reverseStr.length() < 10) {
                return Integer.parseInt(reverseStr);
            }
            if (reverseStr.compareTo(maxStr) > 0) {
                return 0;
            } else {
                return Integer.parseInt(reverseStr);
            }
        } else {
            String s = String.valueOf(x);
            StringBuilder xStr = new StringBuilder(s.substring(1));
            String reverseStr = xStr.reverse().toString();

            // 去掉前面的0
            int firstNotZero = 0;
            while (firstNotZero < reverseStr.length() && reverseStr.charAt(firstNotZero) == '0') {
                firstNotZero++;
            }
            reverseStr = reverseStr.substring(firstNotZero);
            if (reverseStr.length() < 10) {
                return -Integer.parseInt(reverseStr);
            }
            if (reverseStr.compareTo(minStr) > 0) {
                return 0;
            } else {
                return -Integer.parseInt(reverseStr);
            }
        }

    }

}
